package org.study.hadoop.md.ch3;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;
import java.util.Random;

/**
 * 简单随机抽样过滤文本
 */
public class SimpleRandomSampling extends Configured implements Tool {

    public static class SRSMapper extends Mapper<Object, Text, NullWritable, Text> {
        private Random random = new Random();
        private Double percentage;

        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            String strPercentage = context.getConfiguration().get("filter_percentage");
            percentage = Double.parseDouble(strPercentage) / 100.0;
        }

        @Override
        protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            if (random.nextDouble() < percentage) {
                context.write(NullWritable.get(), value);
            }
        }
    }

    @Override
    public int run(String[] args) throws Exception {
        Path outPath = new Path("out");
        Path inPath = new Path("post.txt");
        FileSystem fs = outPath.getFileSystem(getConf());
        if (fs.exists(outPath)) {
            fs.delete(outPath, true);
        }
        getConf().set("filter_percentage", "5");
        Job job = Job.getInstance(getConf(), "SRS");
        job.setJarByClass(SimpleRandomSampling.class);
        job.setMapperClass(SRSMapper.class);
        job.setOutputKeyClass(NullWritable.class);
        job.setOutputValueClass(Text.class);
        job.setNumReduceTasks(0);
        FileInputFormat.addInputPath(job, inPath);
        FileOutputFormat.setOutputPath(job, outPath);
        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static void main(String[] args) throws Exception {
        int res = ToolRunner.run(new Configuration(), new SimpleRandomSampling(), args);
        System.exit(res);
    }
}
